<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.model.Synonym"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
boolean nowy = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
String id = schema+"-"+name;
String action="update";
String save = "Zapisz";
String target_schema="";
String target_name = "";
String target_type = "VIEW";
Synonym ob = null;
if(nowy){
	action="create";
	save = "Utwórz";
	schema=u.getSchemaName();
	name="Nowy synonim";
	target_schema = schema;
}else{
	ob = DbMetaData.getSynonym(u, name, schema);
	target_schema = ob.getTableOwner();
	target_name = ob.getTableName();
	target_type = ob.getObjectType();
}
%>
<div class="container" style="width:500px">
    <div id="<%=id%>-form"></div>
</div>
<script language="JavaScript">

var typeStore = new Ext.data.ArrayStore({
		fields:['t','name'],
		data:[['49','FUNCTION'],['50','PACKAGE'],['48','PROCEDURE'],['38','SEQUENCE'],['-1','SNAPHOT'],['80','SYNONYM'],['32','TABLE'],['39','VIEW'],['-1','JAVA CLASS']]
});

var typeCmb = new Ext.form.ComboBox({
	store: typeStore,
	id: 'type',
	mode: 'local',
	typeAhead: true,
	valueField: 't',
	value:'39',
	displayField: 'name',
	triggerAction: 'all',
	fieldLabel: 'Typ obiektu'
});

var schemaCmb = combo({
	id: 'schema',
	name:'to',
	valueField: 'name',
	displayField: 'name',
	triggerAction: 'all',
	value:'<%=schema%>',
	fieldLabel: 'Schemat'
});

var objectCmb = new Ext.form.ComboBox({
	store: new Ext.data.JsonStore({  
         url:'db/obj.jsp',  
         root:'data',  
         fields: ['name','name'],
         baseParams : {
         	owner:'<%=schema%>',
            t: typeCmb.getRawValue()
        }
     }),
	id: 'name',
	name:'tn',
	valueField: 'name',
	displayField: 'name',
	triggerAction: 'all',
	emptyText: '',
	fieldLabel: 'Objekt'
});

typeCmb.on('select', function(cmb, record, index){ //krok 1  
    objectCmb.clearValue(); //krok 2  
    objectCmb.getStore().reload({ //krok 3  
        params: {
        	owner:schemaCmb.getRawValue(), //krok 4
            t: record.get('t') //krok 5
        }
    });
}, this);
schemaCmb.on('select', function(cmb, record, index){ //krok 1  
    objectCmb.clearValue(); //krok 2  
    objectCmb.getStore().reload({ //krok 3  
        params: {
        	owner: record.get('name'),	//krok 4
            t: typeCmb.getRawValue() //krok 5
        }
    });
}, this);

SynonimForm = Ext.extend(Ext.form.FormPanel, {
    renderTo: '<%=id%>-form',
    iconCls: 'db-synonym-icon',
    frame: true,
    labelAlign: 'left',
    title: '<%=id%>',
    width: 850,
    url:'db/synonym.jsp',
    initComponent : function() {
   		 var config={
        	defaultType: 'textfield',
        	defaults: {
            	anchor: '100%'
       		},
       		monitorValid:true,
       	    items: [
       	    	{fieldLabel: 'Nazwa', name: 'name', allowBlank: false,value:'<%=name %>'<%=(nowy)?"":",readOnly:true"%>},
       	        <%=(nowy)?"combo({emptyText:'"+schema+"'})":"{fieldLabel:'Schemat',name:'schema',allowBlank:false,value:'"+schema+"',readOnly:true}"%>,
       	        {
       	        	xtype:'fieldset',
       	        	defaultType: 'textfield',
       	        	title:'Synonim dla',
		        	defaults: {
		            	anchor: '100%'
		       		},
       	        	items:[
       	        		<%=(nowy)?"typeCmb":"{fieldLabel:'Typ obiektu',allowBlank:false,value:'"+target_type+"',readOnly:true}"%>,
       	        		<%=(nowy)?"schemaCmb":"{fieldLabel:'Schemat',name:'to',allowBlank:false,value:'"+target_schema+"',readOnly:true}"%>,
       	        		<%=(nowy)?"objectCmb":"{fieldLabel:'Objekt',name:'tn',allowBlank:false,value:'"+target_name+"',readOnly:true}"%>
       	        	]
       	        }
       	    ],
       	    buttons:[
  	    	<%=(nowy)?"{"+
       	    	"text: 'Zapisz',"+
       	    	"iconCls: 'icon-save',"+
       	    	"formBind:true,"+
       	    	"scope: this,"+
       	    	"handler:this.submit"+
           	"},":""%>
           	{
           		text: 'Odśwież',
           		scope: this,
                handler: function(btn, ev){
                	this.getForm().load({url:'db/synonym.jsp',params:{name:'${name}',schema:'${schema}',action:'get'},method:'POST'});
            	}
            }]
       };

   		Ext.apply(this, Ext.apply(this.initialConfig, config));
        SynonimForm.superclass.initComponent.apply(this, arguments);
    },
	onRender:function() {
	    SynonimForm.superclass.onRender.apply(this, arguments);
	    this.getForm().waitMsgTarget = this.getEl();
    },
	onLoadClick:function() {
    	this.load({
	    	url:this.url
	    	,waitMsg:'Ładowanie...'
	    	 ,params:{action:'get'},
	    	 failure:this.onFailure
    	});
    },
    submit:function() {
    	this.getForm().submit({
    		url:this.url,
    		scope:this,
    		success:this.onSuccess,
    		failure:this.onFailure,
    		params:{action:'create'},
    		waitMsg:'Trwa zapisywanie danych...'
    	});
   	},
   	onSuccess:function(form, action) {
   		obj = Ext.util.JSON.decode(action.response.responseText);
        var root = Ext.getCmp('api-tree').getRootNode();
    	if( (catNode=root.findChild("t","80"))!=null){
    			catNode.reload();
    	}
   		<%if(nowy){%>
    	Ext.Msg.alert('DbExplorer','Z powodzeniem utworzono nowy synonim');
		var w = Ext.getCmp('create-window');
		if(w){
			w.close();
		}
		<%}%>
    },
    onFailure:function(form, action) {
    		this.showError(action.response.responseText);
    },
    showError:function(msg) {
    	obj = Ext.util.JSON.decode(msg);
    	 title = obj.error.title||'Error';
    	 Ext.Msg.show({
    		title:title,
    	 	msg:obj.error.msg||obj.error,
    	 	modal:true,
    	 	icon:Ext.Msg.ERROR,
    	 	buttons:Ext.Msg.OK
    	 });
    }
});
Ext.onReady(function() {
	Ext.form.Field.prototype.msgTarget = 'side';
    var functionForm = new SynonimForm({
        renderTo: '<%=id%>-form'
    });
});
</script>